package calao.client.ui;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

/** A replacement for default GWT tab panel.
 * This panel does not set width style attribute of inserted widgets.
 */
public class TabPanel
extends Composite
{
	
	public class Tab extends SpacerPanel 
	implements FormListener
	{
		final Label title;
		final int position;
		final String titleText;
		Tab(String title, int position) {
			super(SpacerPanel.VERTICAL);
			this.title = new Label(title, false);
			this.position = position;
			this.titleText = title;
		}
		int compareTo(Tab tab) {
			if (position<tab.position || tab.position==-1) return -1;
			if (position>tab.position || position==-1) return 1;
			return 0;
		}
		public void setTitle(String title)
		{
			this.title.setText(title);
		}
		void setMarked(boolean marked) {
			if (marked) title.setText(titleText+"*");
			else title.setText(titleText);
		}
		public void onChangesAvailable(Form form) {
			setMarked(true);
		}
		public void onChangesCanceled(Form form) { 
			setMarked(false);
		}
		public void onChangesSaved(Form form) { 
			setMarked(false);
		}
		public void add(Widget widget) {
			if (widget instanceof Form) ((Form)widget).addListener(this);
			super.add(widget);
		}
		public int getPosition() {
			return position;
		}
	}

	final com.google.gwt.user.client.ui.TabPanel panel = 
		new com.google.gwt.user.client.ui.TabPanel() {
		public void insert(Widget widget, String tabText, boolean asHTML, int beforeIndex) 
		{
			String width = Elements.getWidth(widget.getElement());
			super.insert(widget, tabText, asHTML, beforeIndex);
			Elements.setWidth(widget.getElement(), width);
		}		
	};

	public TabPanel()
	{
		initWidget(panel);
	}
		
	public Tab newTab(String title, Widget widget, int position)
	{
		Tab tab = new Tab(title, position);
		int index = getTabCount();
		if (position!=-1) {
			for (index=0; index<getTabCount(); index++) {
				if (tab.compareTo(getTab(index))<0) break;
			}
		}
		panel.insert(tab, tab.title, index);
		if (panel.getWidgetCount()==1) panel.selectTab(0);
		if (widget!=null) tab.add(widget);
		return tab;
	}
	
	public Tab newTab(String title, Widget widget)
	{
		return newTab(title, widget, -1);
	}
	
	public Tab newTab(String title)
	{
		return newTab(title, null, -1);
	}

	public Tab getTab(int index)
	{
		return (Tab)panel.getWidget(index);
	}
	
	public Tab getPositionTab(int position)
	{
		for (int index=0; index<getTabCount(); index++) {
			if (getTab(index).position==position) return getTab(index);
		}
		return null;
	}
	
	public int getTabCount()
	{
		return panel.getWidgetCount();
	}
	
	public void remove(Tab tab)
	{
		panel.remove(tab);
	}
	
}
